package com.wyh.trans.controller;

import com.wyh.trans.mapper.UserInfoMapper;
import com.wyh.trans.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/u1")
    public String insert(String userName, String password){
        //开启事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        //用户注册
        userService.insert("tjy","54656");
        //提交事务
//        dataSourceTransactionManager.commit(transaction);
        //回滚事务
        dataSourceTransactionManager.rollback(transaction);
        return "注册成功";
    }

    @RequestMapping("/u2")
    @Transactional
    public String insert2(String userName, String password){
        userService.insert("tjy","54656");
        try {
            int a = 10/0;
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
        return "注册成功";
    }

    @RequestMapping("/u3")
    @Transactional(rollbackFor = {Exception.class,IOException.class})
    public String insert3(String userName, String password) throws IOException {
        userService.insert("tjy","54656");
        if (true){
            throw new IOException();
        }
        return "注册成功";
    }
}
